package com.squirrel.common.config;

import com.squirrel.common.shiro.JwtFilter;
import com.squirrel.common.shiro.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 集成shiro
 * @Author 关远键
 * @Version v1.0.0
 * @Date 2021/11/7 22:38
 */
@Configuration
public class ShiroConfig {

    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 密码加密
//        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
//        matcher.setHashAlgorithmName("MD5");
//        matcher.setHashIterations(2);
//        userRealm.setCredentialsMatcher(matcher);

        // 认证缓存
        AbstractCacheManager cacheManager = new MemoryConstrainedCacheManager();
        manager.setCacheManager(cacheManager);

        manager.setRealm(userRealm);
        return manager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);

        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());
        bean.setFilters(filterMap);

        //配置系统的受限资源以及对应的过滤器
        Map<String, String> ruleMap = new HashMap<>();
        ruleMap.put("/swagger-ui/**", "anon"); //登录路径、注册路径都需要放行不进行拦截
        ruleMap.put("/druid/**", "anon");
        ruleMap.put("/api/**", "anon");
//        ruleMap.put("/api/**", "jwt");  // 表示对所有资源起作用，使用JwtFilter
        bean.setFilterChainDefinitionMap(ruleMap);
        return bean;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/swagger-ui/**", "anon");
//        definition.addPathDefinition("/api/user/getAuthorInfo/**", "authc");

//        definition.addPathDefinition("/api/user/*", "perms[user:vip]");

        return definition;
    }
}
